package com.jumi.microservice.service.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jumi.microservice.common.constant.DelFlag;
import com.jumi.microservice.common.utils.DateUtil;
import com.jumi.microservice.config.ExpireTimeConfig;
import com.jumi.microservice.constant.compensation.AfterSaleEnum;
import com.jumi.microservice.constant.compensation.AfterSaleStatusEnum;
import com.jumi.microservice.constant.compensation.CheckStatusEnum;
import com.jumi.microservice.constant.refundgoods.CancelUserFlagEnum;
import com.jumi.microservice.constant.refundgoods.ExpireTime;
import com.jumi.microservice.constant.refundgoods.RefundGoodsStatusEnum;
import com.jumi.microservice.constant.refundgoods.RefundTypeEnum;
import com.jumi.microservice.dto.order.OrderLogRequest;
import com.jumi.microservice.dto.refundgoods.RefundGoodsAutoCancelRequest;
import com.jumi.microservice.dto.refundgoods.RefundGoodsStatusRequest;
import com.jumi.microservice.dto.serviceDto.UpdateAfterSealStatusRequest;
import com.jumi.microservice.entity.Compensation;
import com.jumi.microservice.entity.RefundGoods;
import com.jumi.microservice.mapper.CompensationMapper;
import com.jumi.microservice.mapper.RefundGoodsMapper;
import com.jumi.microservice.service.IOrderDubboService;
import com.jumi.microservice.service.IOrderService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author scw
 * @date 2020/12/15
 */
@Service
public class RefundGoodsCommonService {
    @Resource
    private CompensationMapper compensationMapper;
    @Resource
    private RefundGoodsMapper refundGoodsMapper;
    @DubboReference
    private IOrderDubboService iOrderDubboService;
    @DubboReference
    private IOrderService iOrderService;
    @Resource
    private ExpireTimeConfig expireTimeConfig;

    /**
     * 售后自动取消通用方法
     *
     * @param request
     */
    public void autoCancel(RefundGoodsAutoCancelRequest request) {
        Long operatorId = 0L;
        String operatorName = "过期自动取消";
        if (request.getRefundType() == RefundTypeEnum.REFUND_TYPE_GOODS.getCode().byteValue()) {
            //用户申请已提交，等待平台审核。时间2天 【0-待处理】
            if (request.getStatus() == RefundGoodsStatusEnum.STATUS_DEAL_WITH.getCode().byteValue() &&
                    DateUtil.getDateAfterMinute(request.getCreateTime(), Integer.parseInt(expireTimeConfig.getDiffMinuteOne())).before(new Date())) {
                RefundGoodsStatusRequest refundGoodsStatusRequest = new RefundGoodsStatusRequest();
                refundGoodsStatusRequest.setOperatorId(operatorId);
                refundGoodsStatusRequest.setOperatorName(operatorName);
                this.autoCcancelRefundGoods(operatorId, operatorName, request.getUid(), request.getRefundId());
            }
            /*
             * 平台审核通过，等待用户上传单号。时间为2天 【1-待收货 未上传单号】
             * 用户已发货，等待平台收货。时间7天 【1-待收货 已上传单号】
             */
            if (request.getStatus() == RefundGoodsStatusEnum.STATUS_RECEIVED.getCode().byteValue()) {
                if ("".equals(request.getLogisticsNo()) || null == request.getLogisticsNo()) {
                    //平台审核通过，等待用户上传单号。时间为2天 【1-待收货 未上传单号】
                    if (DateUtil.getDateAfterMinute(request.getDealWithTime(), Integer.parseInt(expireTimeConfig.getDiffMinuteTwo())).before(new Date())) {
                        RefundGoodsStatusRequest refundGoodsStatusRequest = new RefundGoodsStatusRequest();
                        refundGoodsStatusRequest.setOperatorId(operatorId);
                        refundGoodsStatusRequest.setOperatorName(operatorName);
                        this.autoCcancelRefundGoods(operatorId, operatorName, request.getUid(), request.getRefundId());
                    }
                } else {
                    //用户已发货，等待平台收货。时间7天 【1-待收货 已上传单号】
                    if (DateUtil.getDateAfterMinute(request.getLogisticsTime(), Integer.parseInt(expireTimeConfig.getDiffMinuteThree())).before(new Date())) {
                        RefundGoodsStatusRequest refundGoodsStatusRequest = new RefundGoodsStatusRequest();
                        refundGoodsStatusRequest.setOperatorId(operatorId);
                        refundGoodsStatusRequest.setOperatorName(operatorName);
                        this.autoCcancelRefundGoods(operatorId, operatorName, request.getUid(), request.getRefundId());
                    }
                }
            } else if (request.getStatus() == RefundGoodsStatusEnum.STATUS_CHECK.getCode().byteValue()) {
                //用户申请已提交，等待平台审核---->平台处理通过---->平台选择弃货---->等待财务审核，共用时间。时间2天 【2-待审核】
                if (DateUtil.getDateAfterMinute(request.getCreateTime(), Integer.parseInt(expireTimeConfig.getDiffMinuteOne())).before(new Date())) {
                    RefundGoodsStatusRequest refundGoodsStatusRequest = new RefundGoodsStatusRequest();
                    refundGoodsStatusRequest.setOperatorId(operatorId);
                    refundGoodsStatusRequest.setOperatorName(operatorName);
                    this.autoCcancelRefundGoods(operatorId, operatorName, request.getUid(), request.getRefundId());
                    //查询信息
                    QueryWrapper<Compensation> queryWrapperCompensation = new QueryWrapper<>();
                    queryWrapperCompensation.eq("refund_id", request.getRefundId());
                    queryWrapperCompensation.eq("after_sale_type", AfterSaleEnum.AFTER_SALE_QHTK.getCode());
                    queryWrapperCompensation.eq("check_status", CheckStatusEnum.CHECK_STATUS_WAIT.getCode());
                    queryWrapperCompensation.eq("original_order_id", request.getOrderId());
                    queryWrapperCompensation.eq("compensation_goods_id", request.getGoodsId());
                    queryWrapperCompensation.eq("del_flag", DelFlag.NORMAL);
                    queryWrapperCompensation.orderByDesc("id");
                    queryWrapperCompensation.last("limit 1");
                    Compensation compensation = compensationMapper.selectOne(queryWrapperCompensation);
                    if (compensation != null) {
                        compensation.setCheckStatus(CheckStatusEnum.CHECK_STATUS_REFUSE.getCode().byteValue());
                        compensation.setCheckRemark(operatorName);
                        compensation.setCheckOperatorId(operatorId);
                        compensation.setCheckOperatorName(operatorName);
                        compensation.setCheckTime(new Date());
                        compensationMapper.updateById(compensation);
                    }
                }
            }
        }
    }

    /**
     * 退货退款取消
     *
     * @param operatorId
     * @param operatorName
     * @param uid
     * @param refundId
     */
    private void autoCcancelRefundGoods(Long operatorId, String operatorName, Long uid, Integer refundId) {
        List<Integer> statusVals = new ArrayList<Integer>();
        statusVals.add(RefundGoodsStatusEnum.STATUS_DEAL_WITH.getCode());
        statusVals.add(RefundGoodsStatusEnum.STATUS_RECEIVED.getCode());
        statusVals.add(RefundGoodsStatusEnum.STATUS_CHECK.getCode());
        //查询信息
        QueryWrapper<RefundGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("buyer_id", uid);
        queryWrapper.eq("id", refundId);
        queryWrapper.in("status", statusVals);
        RefundGoods refundGoods = refundGoodsMapper.selectOne(queryWrapper);
        if (refundGoods != null) {
            refundGoods.setStatus(RefundGoodsStatusEnum.STATUS_CANCEL.getCode().byteValue());
            refundGoods.setCancelOperatorId(operatorId);
            refundGoods.setCancelOperatorName(operatorName);
            refundGoods.setCancelTime(new Date());
            refundGoods.setCancelUserFlag(CancelUserFlagEnum.USER_FLAG_CUSTOMER.getCode().byteValue());
            if (refundGoodsMapper.updateById(refundGoods) > 0) {
                /*
                 * 操作日志表插入相关信息
                 */
                String logInfo = "售后处理-过期自动取消";
                if (refundGoods.getRefundType() == RefundTypeEnum.REFUND_TYPE_GOODS.getCode().byteValue()) {
                    logInfo += "退货退款";
                } else {
                    logInfo += "退款";
                }
                operatorName = "买家";
                //用户标识，1 前端用户， 2 后端管理员
                Byte userFlag = CancelUserFlagEnum.USER_FLAG_CUSTOMER.getCode().byteValue();
                OrderLogRequest orderLogRequest = new OrderLogRequest();
                orderLogRequest.setLog(logInfo);
                orderLogRequest.setOperatorId(operatorId);
                orderLogRequest.setOperatorName(operatorName);
                orderLogRequest.setUserFlag(userFlag);
                orderLogRequest.setOrderSn(refundGoods.getOriginalOrderNo());
                iOrderDubboService.addOrderLog(orderLogRequest);
                /*
                 * 订单商品表更新售后状态
                 * 售后状态:
                 *      0-正常 1-已退款
                 *      2-退货审核中 3-已退货退款 4-退货退款拒绝
                 *      5-补发审核中 6-已补发 7-补发拒绝
                 *      8-补偿审核中 9-已补偿 10-补偿拒绝
                 *      11-补邮审核中 12-已补邮费 13-补邮拒绝
                 *      14-换货申请中 15-换货同意  16-换货拒绝
                 *      17-补发漏发审核中 18-已补发漏发 19-补发漏发拒绝
                 * after_seal_status = 0
                 */
                //int afterSealStatus = 0;
                int afterSealStatus = AfterSaleStatusEnum.NORMAL.getCode();
                UpdateAfterSealStatusRequest updateAfterSealStatusRequest = new UpdateAfterSealStatusRequest();
                updateAfterSealStatusRequest.setOrderId(refundGoods.getOriginalOrderId());
                updateAfterSealStatusRequest.setGoodsId(refundGoods.getRefundGoodsId());
                updateAfterSealStatusRequest.setAfterSealStatus((byte) afterSealStatus);
                iOrderService.updateAfterSealStatus(updateAfterSealStatusRequest);
            }
        }
    }
}
